package com.api.workflow.web;


import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.json.JSONException;
import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.workflow.webservices.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.*;


/*
 * sap调OA的接口
 * */
@Path("/yn/sap/oa")
public class SAPOAYNController extends BaseBean {
    public static void main(String[] args) {
        System.out.println("ss");
    }

    /**
     * 接口6  SAP付款入账凭证数据回传OA
     * 流程：资产减值申请
     *
     * @return
     */
    @POST
    @Path("/updateSapfkpzh")
    @Produces(MediaType.APPLICATION_JSON)
    public String updateSapfkpzh(@Context HttpServletRequest request, @Context HttpServletResponse response, @Valid @RequestBody String requestData) {
        BaseBean baseBean = new BaseBean();

        Map<String, Object> map = new HashMap<>();
        String fieldName = "";

        JSONObject object = new JSONObject();
        try {
            JSONObject jsonObject1 = JSONObject.parseObject(requestData);
            Integer requestId = jsonObject1.getInteger("requestId");
            String fieldValue = jsonObject1.getString("sapfkpzh");//凭证号
            baseBean.writeLog("wyq===SAPOA6===requestid" + requestId);


            WorkflowServiceImpl service = new WorkflowServiceImpl();
            WorkflowRequestInfo wri = service.getWorkflowRequest(requestId, 1, 0);
            com.alibaba.fastjson.JSONObject jsonObject = new JSONObject();
            String wriInfo = jsonObject.toJSONString(wri);
            baseBean.writeLog("wyq===SAPOA6===wriInfo" + wriInfo);
            //更新主表凭证号
            WorkflowMainTableInfo mainTableInfo = wri.getWorkflowMainTableInfo();
            WorkflowRequestTableRecord[] requestRecords = mainTableInfo.getRequestRecords();
            for (WorkflowRequestTableRecord requestRecord : requestRecords) {
                WorkflowRequestTableField[] tableFields = requestRecord.getWorkflowRequestTableFields();
                for (WorkflowRequestTableField tableField : tableFields) {
                    map.put(tableField.getFieldName(), tableField.getFieldValue());
                }
            }

            if (map.containsKey("sapfkpzh")) {
                fieldName = "sapfkpzh";
            } else {
                fieldName = "fhjg";
            }
            String tableName = wri.getWorkflowMainTableInfo().getTableDBName();
            // 判断凭证号是否存在
            boolean isExist = false;
            RecordSet re = new RecordSet();
            re.executeQuery("select " + fieldName + " from " + tableName + "  where  requestid = ?", requestId);
            if (re.next()) {
                String pzh = re.getString(fieldName);
                if (pzh != null && !pzh.equals("") && !pzh.equals("null")) {
                    fieldValue = pzh + "," + fieldValue;
                    isExist = true;
                }
            }

            RecordSet recordSet = new RecordSet();
            String updateMainTableName = "update " + tableName + " set " + fieldName + " = ?  where  requestid = ? ";
            boolean b = recordSet.executeUpdate(updateMainTableName, fieldValue, requestId);
            baseBean.writeLog("wyq===SAPOA6===b" + b);
            if (!isExist && b) {
                //归档
                WorkflowRequestOperatePAImpl operatePA = ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
                ReqOperateRequestEntity requestEntity = new ReqOperateRequestEntity();
                Integer userid = Integer.valueOf(baseBean.getPropValue("YNSap", "userid"));
                User user = new User(userid);
                requestEntity.setRequestId(requestId);
                PAResponseEntity entity = operatePA.submitRequest(user, requestEntity);
                object.put("code", entity.getCode());
                object.put("errmsg", entity.getErrMsg());
            } else {
                object.put("code", "ERROR");
                object.put("errmsg", "凭证号更新失败");
            }


        } catch (Exception e) {
            e.printStackTrace();
            object.put("code", "ERROR");
            object.put("errmsg", e.toString());
        }
        return object.toJSONString();
    }

    /**
     * 接口16  采购PR单
     *
     * @return
     */
    @POST
    @Path("/procurementRequest")
    @Produces(MediaType.APPLICATION_JSON)
    public String ProcurementRequest(@Context HttpServletRequest request, @Context HttpServletResponse response, @Valid @RequestBody String Data) {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        writeLog("=====ProcurementRequest========Data:" + Data);
        RecordSet recordSet = new RecordSet();
        String select = "select * from uf_cgsqd where cgsqbh = ? and cgsqxxm = ?";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JSONArray jsonArray = JSONObject.parseArray(Data);
            writeLog("=====ProcurementRequest========jsonArray:" + jsonArray.toString());
            List<Map<String, Object>> addList = new ArrayList<>();
            List<Map<String, Object>> updateList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                Map<String, Object> bodyMap = objectMapper.readValue(jsonObject.toString(), Map.class);
                Object cgsqbh = bodyMap.get("cgsqbh");
                Object cgsqxxm = bodyMap.get("cgsqxxm");
                Object cgz = bodyMap.get("cgz");//采购组
                String hqry = null;
                String csry = null;
                if (!StringUtil.isNullOrEmpty((String) cgz)) {
                    RecordSet recordSet1 = new RecordSet();
                    recordSet1.executeQuery("select whry,cgzcsry from uf_cgzb where bm=?", cgz);
                    recordSet1.next();
                    hqry = Util.null2String(recordSet1.getString("whry"));
                    csry = Util.null2String(recordSet1.getString("cgzcsry"));
                    writeLog("hqryhqryhqryhqry" + hqry);
                    writeLog("csrycsrycsrycsry" + csry);
                }
                if (StringUtil.isNullOrEmpty(hqry)) {
                    hqry = null;
                }
                if (StringUtil.isNullOrEmpty(csry)) {
                    csry = null;
                }
                bodyMap.put("hqry", hqry);
                bodyMap.put("csry", csry);
                Object wlbm = bodyMap.get("wlbm");
                recordSet.executeQuery("select wlz from uf_wlbd where wlbm=?", wlbm);
                recordSet.next();
                String wlz = recordSet.getString("wlz");
                bodyMap.put("wlz", wlz);
                if (cgsqbh == null) {
                    objectObjectHashMap.put("status", "error");
                    objectObjectHashMap.put("message", "采购申请编号不能为空");
                    return JSONObject.toJSONString(objectObjectHashMap);
                }
                if (cgsqxxm == null) {
                    objectObjectHashMap.put("status", "error");
                    objectObjectHashMap.put("message", "采购申请行项目不能为空");
                    return JSONObject.toJSONString(objectObjectHashMap);
                }
                String xqjh = String.valueOf(bodyMap.get("xqjh"));
                String xqbm = String.valueOf(bodyMap.get("xqbm"));
                String xqbmid = "";
                if (!StringUtil.isNullOrEmpty(xqbm)) {
                    recordSet.executeQuery("select bm from uf_bmdyb where sapbm=?", xqbm);
                    recordSet.next();
                    xqbmid = recordSet.getString("bm");
                }
                bodyMap.put("xqbm", xqbmid);
                String requestid = "";
                String workflowid = "";
                String creater = "";
                if (!StringUtil.isNullOrEmpty(xqjh)) {
                    recordSet.executeQuery("select requestid,creater,workflowid from workflow_requestbase  where  requestmark=?", xqjh);
                    recordSet.next();
                    requestid = Util.null2String(recordSet.getString("requestid"));
                    creater = Util.null2String(recordSet.getString("creater"));
                    workflowid = Util.null2String(recordSet.getString("workflowid"));
                }
                writeLog("requestid-----xg" + requestid);
                writeLog("requestid-----xg" + workflowid);
                if (!StringUtil.isNullOrEmpty(requestid) && !StringUtil.isNullOrEmpty(workflowid)) {
                    RecordSet rs = new RecordSet();
                    rs.execute("select tablename from workflow_base a,workflow_bill b where a.formid=b.id and a.id=" + workflowid);
                    rs.next();
                    //获取主表名
                    String maintable = Util.null2String(rs.getString("tablename"));
                    rs.executeUpdate("update " + maintable + " set cgsqbh='" + cgsqbh + "' where requestid=" + requestid);
                }
                bodyMap.put("xglc", requestid);
                bodyMap.put("xqjhcjr", creater);
                writeLog("bodyMapbodyMapbodyMapbodyMap-----bodyMap" + bodyMap);
                recordSet.executeQuery(select, cgsqbh.toString(), cgsqxxm.toString());
                recordSet.next();
                recordSet.getCounts();
                if (recordSet.getCounts() == 0) {

                    addList.add(bodyMap);
                } else {
                    updateList.add(bodyMap);
                }
            }
            //新增
            writeLog("======ProcurementRequest=======stringObjectMap:" + JSONObject.toJSONString(addList));
            int modeId = getModeId("uf_cgsqd");
            for (Map<String, Object> bodyMap : addList) {
                insetModeData("uf_cgsqd", bodyMap, 1, modeId);
            }
            //更新;
            writeLog("=======ProcurementRequest======stringObjectMap:" + JSONObject.toJSONString(updateList));
            Map<String, Object> whereMap = new HashMap<>();
            for (int i = 0; i < updateList.size(); i++) {
                Map<String, Object> updateMap = updateList.get(i);
                whereMap.put("cgsqbh", updateMap.get("cgsqbh"));
                whereMap.put("cgsqxxm", updateMap.get("cgsqxxm"));
                updateMap.put("dqzt", "0");
                updateModeData("uf_cgsqd", updateMap, whereMap);
            }
//            HashMap<String, Object> updateObjectHashMap1 = new HashMap<>();
//            updateObjectHashMap1.put("dqzt", "0");
//            updateModeData("uf_cgsqd", updateObjectHashMap1, whereMap);
            objectObjectHashMap.put("status", "ok");
        } catch (Exception e) {
            objectObjectHashMap.put("status", "error");
            writeLog("=======ProcurementRequest======error:" + e.getMessage());
        }
        return JSONObject.toJSONString(objectObjectHashMap);
    }


    /**
     * 新增接口  插入数据到表uf_dhdxx
     *
     * @return
     */
    @POST
    @Path("/insertDhdxx")
    @Produces(MediaType.APPLICATION_JSON)
    public String insertDhdxx(@Context HttpServletRequest request, @Context HttpServletResponse response, @Valid @RequestBody String Data) {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        writeLog("=====insertDhdxx========Data:" + Data);
        RecordSet recordSet = new RecordSet();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JSONArray jsonArray = JSONObject.parseArray(Data);
            writeLog("======insertDhdxx=======jsonArray:" + jsonArray.toString());
            List<Map<String, Object>> addList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Map<String, Object> bodyMap = objectMapper.readValue(jsonObject.toString(), Map.class);

                addList.add(bodyMap);

            }
            //新增
            writeLog("=======insertDhdxx======stringObjectMap:" + JSONObject.toJSONString(addList));
            int modeId = getModeId("uf_dhdxx");
            for (Map<String, Object> bodyMap : addList) {
                insetModeData("uf_dhdxx", bodyMap, 1, modeId);
            }

            objectObjectHashMap.put("status", "ok");
        } catch (Exception e) {
            objectObjectHashMap.put("status", "error");
            writeLog("=========insertDhdxx====error:" + e.getMessage());
        }
        return JSONObject.toJSONString(objectObjectHashMap);
    }


    /**
     * 新增接口  插入数据到表uf_nbjhd
     *
     * @return
     */
    @POST
    @Path("/insertNbjhd")
    @Produces(MediaType.APPLICATION_JSON)
    public String insertNbjhd(@Context HttpServletRequest request, @Context HttpServletResponse response, @Valid @RequestBody String Data) {

        Map<String, Object> resultMap = new HashMap<>();
        writeLog("========insertNbjhd=====Data:" + Data);
        RecordSet recordSet = new RecordSet();
        String select = "select * from uf_nbjhd where VBELN = ?";
        String mainId = "";
        Map<String, Object> mainMap = new HashMap<>();
        int modeId = getModeId("uf_nbjhd");
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JSONArray jsonArray = JSONObject.parseArray(Data);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Map<String, Object> bodyMap = objectMapper.readValue(jsonObject.toString(), Map.class);
                Object VBELN = bodyMap.get("VBELN");
                if (VBELN == null || "".equals(VBELN)) {
                    resultMap.put("status", "error");
                    resultMap.put("message", "交货单号不能为空");
                    return JSONObject.toJSONString(resultMap);
                }
                //主表数据
                mainMap.putAll(bodyMap);
                mainMap.remove("DETAILS");
                //明细表数据
                String DETAILS = jsonObject.getString("DETAILS");
                writeLog("========insertNbjhd=====DETAILS:" + DETAILS);
                if (DETAILS == null || "".equals(DETAILS)) {
                    resultMap.put("status", "error");
                    resultMap.put("message", "明细不能为空");
                    return JSONObject.toJSONString(resultMap);
                }
                JSONArray detailsArray = JSONObject.parseArray(Data);
                writeLog("========insertNbjhd=====detailsArray:" + detailsArray);
                recordSet.executeQuery(select, VBELN.toString());
                if (recordSet.next()) {
                    mainId = recordSet.getString("ID");
                }
                if (recordSet.getCounts() == 0) {//新增
                    boolean b1 = insetModeData("uf_nbjhd", mainMap, 1, modeId);
                    writeLog("======insertNbjhd=======insert:" + b1);
                    //查mainid
                    recordSet.executeQuery(select, VBELN.toString());
                    if (recordSet.next()) {
                        mainId = recordSet.getString("ID");
                    }
                    writeLog("=======insertNbjhd======mainId1:" + mainId);
                    for (int j = 0; j < detailsArray.size(); j++) {
                       JSONObject detailsArrayJSONObject = detailsArray.getJSONObject(j);
                        Map<String, Object> detailMap = objectMapper.readValue(detailsArrayJSONObject.toString(), Map.class);
                        detailMap.put("mainId", mainId);
                        writeLog("========insertNbjhd=====mainId2:" + mainId);
                        boolean b = insetDetailData("uf_nbjhd_dt1", detailMap);
                        writeLog("========insertNbjhd=====insertDetail:" + b);
                    }

                } else {
                    for (int j = 0; j < detailsArray.size(); j++) {
                        JSONObject detailsArrayJSONObject = detailsArray.getJSONObject(j);
                        Map<String, Object> detailMap = objectMapper.readValue(detailsArrayJSONObject.toString(), Map.class);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("LFIMG", detailMap.get("LFIMG"));
                        Object posnr = detailMap.get("POSNR");
                        if (posnr == null || "".equals(posnr)) {
                            resultMap.put("status", "error");
                            resultMap.put("message", "明细行号不能为空");
                            return JSONObject.toJSONString(resultMap);
                        }
                        //查询明细表
                        String selectDetail = "select * from uf_nbjhd_dt1 where POSNR = ? AND MAINID = ?";
                        recordSet.executeQuery(selectDetail, posnr.toString(), mainId);
                        if (recordSet.next()) {//修改明细表

                            Map<String, Object> whereMap = new HashMap<>();
                            whereMap.put("POSNR", posnr.toString());
                            whereMap.put("mainId", mainId);
                            boolean b = updateModeData("uf_nbjhd_dt1", map, whereMap);
                            writeLog("=======insertNbjhd======updateDetail11:" + b);
                        } else {//新增明细表
                            detailMap.put("mainId", mainId);
                            boolean b = insetDetailData("uf_nbjhd_dt1", detailMap);
                            writeLog("=====insertNbjhd========insertDetail22:" + b);
                        }
                    }
                }
            }
            resultMap.put("status", "ok");
        } catch (Exception e) {
            resultMap.put("status", "error");
            resultMap.put("message", e.toString());
            writeLog("========insertNbjhd=====error:" + e.getMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }


    /**
     * 新增接口  插入数据到表uf_sapgysxx
     *
     * @return
     */
    @POST
    @Path("/insertGysxx")
    @Produces(MediaType.APPLICATION_JSON)
    public String insertGysxx(@Context HttpServletRequest request, @Context HttpServletResponse response, @Valid @RequestBody String Data) {

        Map<String, Object> resultMap = new HashMap<>();
        writeLog("=======insertGysxx======Data:" + Data);
        writeLog("====insertGysxx=========Cleaned Data:" + Data);
        writeLog("======insertGysxx=======Data:" + Data);
        System.out.println("xdffvfd" + Data);
        RecordSet recordSet = new RecordSet();
        String select = "select * from uf_sapgysxx where gysbm = ?";
        String mainId = "";
        int modeId = getModeId("uf_sapgysxx");
        Map<String, Object> resultObject = new HashMap<>();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JSONArray jsonArray = JSONObject.parseArray(Data);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Map<String, Object> bodyMap = objectMapper.readValue(jsonObject.toString(), Map.class);
                Object PARTNER = bodyMap.get("PARTNER");
                if (PARTNER == null || "".equals(PARTNER)) {
                    resultMap.put("status", "error");
                    resultMap.put("message", "业务伙伴编码不能为空");
                    return JSONObject.toJSONString(resultMap);
                }
                //主表数据
                resultObject.put("gysbm", Util.null2String(bodyMap.get("PARTNER")));
                resultObject.put("ywhbyy", Util.null2String(bodyMap.get("LANGU")));
                resultObject.put("ywhblb", Util.null2String(bodyMap.get("BUTYPE")));
                resultObject.put("ywhbfz", Util.null2String(bodyMap.get("BUGROUP")));
                resultObject.put("ywhbmc1", Util.null2String(bodyMap.get("NAMEORG")));
                resultObject.put("ywhbmc2", Util.null2String(bodyMap.get("NAMEORG")));
                resultObject.put("jc", Util.null2String(bodyMap.get("BUSORT1")));
                resultObject.put("yxtbm", Util.null2String(bodyMap.get("BUSORT2")));
                resultObject.put("wyxzxlb", Util.null2String(bodyMap.get("TYPE")));
                resultObject.put("wyxsbzx", Util.null2String(bodyMap.get("IDNUMBER")));
                resultObject.put("sjbs", Util.null2String(bodyMap.get("sjbs")));
                resultObject.put("gsdm", Util.null2String(bodyMap.get("gsdm")));


                resultObject.put("frdb", Util.null2String(bodyMap.get("ZTSD_KHLXR-ZQYFR")));
                resultObject.put("zczjwy", Util.null2String(bodyMap.get("ZTSD_KHLXR-ZZCZB")));
                resultObject.put("ygrs", Util.null2String(bodyMap.get("ZTSD_KHLXR-ZYGRS")));
                resultObject.put("clsl", Util.null2String(bodyMap.get("ZTSD_KHLXR-ZCLSL")));
                resultObject.put("ywhbsh", Util.null2String(bodyMap.get("DFKKBPTAXNUM-AXNUM")));
                resultObject.put("xsdq", Util.null2String(bodyMap.get("T171T-BZTXT")));
                resultObject.put("ywhbszjtmc", Util.null2String(bodyMap.get("BUT000-NAME3+NAME4")));
                resultObject.put("zxbdm", Util.null2String(bodyMap.get("KNA1-BAHNE")));
                resultObject.put("rbdm", Util.null2String(bodyMap.get("KNA1-BAHNS")));
                resultObject.put("khjb", Util.null2String(bodyMap.get("T151T-KTEXT")));
                resultObject.put("ywhbzgb", Util.null2String(bodyMap.get("KNA1-LAND1")));
                resultObject.put("cs", Util.null2String(bodyMap.get("KNA1-ORT01")));
                resultObject.put("sf", Util.null2String(bodyMap.get("KNA1-REGIO")));
                resultObject.put("yzbm", Util.null2String(bodyMap.get("KNA1-PSTLZ")));
                resultObject.put("khzcdz", Util.null2String(bodyMap.get("ADRC-STREET+STR_SUPPL1")));
                resultObject.put("khtxdz", Util.null2String(bodyMap.get("ADRC-STR_SUPPL2+STR_SUPPL3")));


                //明细表数据
                com.alibaba.fastjson.JSONArray detailArray = new com.alibaba.fastjson.JSONArray();
                com.alibaba.fastjson.JSONArray detailArray1 = new com.alibaba.fastjson.JSONArray();
                Object DETAILS = bodyMap.get("DETAILS");
                if (DETAILS != null && !"".equals(DETAILS)) {
                    com.alibaba.fastjson.JSONArray detailsArray = JSONObject.parseArray(JSONObject.toJSONString(DETAILS));
                    for (int i1 = 0; i1 < detailsArray.size(); i1++) {
                        JSONObject detailObject = detailsArray.getJSONObject(i1);
                        Map<String, Object> detailMap = new HashMap<>();
                        detailMap.put("dzlx", detailObject.getString("ADRKIND"));
                        detailMap.put("gjdqdm", detailObject.getString("COUNTRY"));
                        detailMap.put("dq", detailObject.getString("REGION"));
                        detailMap.put("cs1", detailObject.getString("CITY1"));
                        detailMap.put("jd", detailObject.getString("STREET"));
                        detailMap.put("yzxx", detailObject.getString("POSTCODE1"));
                        detailArray.add(detailMap);
                        //查询银行信息
                        com.alibaba.fastjson.JSONArray bankt = detailObject.getJSONArray("BANKT");
                        for (int i2 = 0; i2 < bankt.size(); i2++) {
                            JSONObject detailObject1 = bankt.getJSONObject(i2);
                            Map<String, Object> detailMap1 = new HashMap<>();
                            detailMap1.put("yxszgj", detailObject1.getString("BANKS"));
                            detailMap1.put("yxlxh", detailObject1.getString("BANKL"));
                            detailMap1.put("yxzh", detailObject1.getString("BANKN"));
                            detailMap1.put("zhcyr", detailObject1.getString("KOINH"));
                            detailMap1.put("zhmc", detailObject1.getString("ACCNAME"));
                            detailMap1.put("zhlxwb", detailObject1.getString("BKEXT"));
                            String lhlxwb = Util.null2String(detailObject1.getString("BKEXT"));
                            if (lhlxwb.equals("电汇账户")) {
                                detailMap1.put("zhlx", "0");
                            } else if (lhlxwb.equals("承兑账户")) {
                                detailMap1.put("zhlx", "1");
                            } else if (lhlxwb.equals("承兑+电汇")){
                                detailMap1.put("zhlx", "2");
                            }
                            detailMap1.put("yxmc", detailObject1.getString("BANKA"));
                            detailArray1.add(detailMap1);
                        }
                    }
                }


                recordSet.executeQuery(select, PARTNER.toString());
                if (recordSet.next()) {
                    mainId = recordSet.getString("ID");
                }
                if (recordSet.getCounts() == 0) {//新增
                    writeLog("=========insertGysxx====resultObject:" + JSONObject.toJSONString(resultObject));
                    boolean b1 = insetModeData("uf_sapgysxx", resultObject, 1, modeId);
                    writeLog("========insertGysxx=====insert:" + b1);
                    //查mainid
                    recordSet.executeQuery(select, PARTNER.toString());
                    if (recordSet.next()) {
                        mainId = recordSet.getString("ID");
                    }
                    writeLog("=========insertGysxx====mainId1:" + mainId);
                    for (int j = 0; j < detailArray.size(); j++) {
                        JSONObject detailsArrayJSONObject = detailArray.getJSONObject(j);
                        Map<String, Object> detailMap = objectMapper.readValue(detailsArrayJSONObject.toString(), Map.class);
                        detailMap.put("mainId", mainId);
                        writeLog("=========insertGysxx====uf_sapgysxx_dt4:" + JSONObject.toJSONString(detailMap));
                        boolean b = insetDetailData("uf_sapgysxx_dt4", detailMap);
                        writeLog("========insertGysxx=====insertDetail:" + b);
                    }

                    for (int j = 0; j < detailArray1.size(); j++) {
                        JSONObject detailsArrayJSONObject = detailArray1.getJSONObject(j);
                        Map<String, Object> detailMap = objectMapper.readValue(detailsArrayJSONObject.toString(), Map.class);
                        detailMap.put("mainId", mainId);
                        writeLog("=========insertGysxx====uf_sapgysxx_dt1:" + JSONObject.toJSONString(detailMap));
                        boolean b = insetDetailData("uf_sapgysxx_dt1", detailMap);
                        writeLog("========insertGysxx=====insertDetail1:" + b);
                    }

                } else {
                    //修改主表
                    Map<String, Object> whereMainMap = new HashMap<>();
                    whereMainMap.put("gysbm", PARTNER.toString());
                    boolean b = updateModeData("uf_sapgysxx", resultObject, whereMainMap);
                    writeLog("==========insertGysxx===updateModeData:" + b);
                    //修改明细表
                    for (int j = 0; j < detailArray.size(); j++) {
                        JSONObject detailsArrayJSONObject = detailArray.getJSONObject(j);
                        Map<String, Object> detailMap = objectMapper.readValue(detailsArrayJSONObject.toString(), Map.class);
                        Map<String, Object> whereMap = new HashMap<>();
                        whereMap.put("mainId", mainId);
                        writeLog("=========updateGysxx====uf_sapgysxx_dt4+detailMap:" + JSONObject.toJSONString(detailMap));
                        writeLog("=========updateGysxx====uf_sapgysxx_dt4+whereMap:" + JSONObject.toJSONString(whereMap));
                        boolean b1 = updateModeData("uf_sapgysxx_dt4", detailMap, whereMap);
                        writeLog("========insertGysxx=====updateDetail11:" + b1);
                    }
                    RecordSet recordSet1 = new RecordSet();
                    boolean b1 = recordSet1.executeUpdate("delete from uf_sapgysxx_dt1 where mainId = ?", mainId);
                    writeLog("========insertGysxx=====deleteDetail1:" +b1);
                    //修改明细表
                    for (int j = 0; j < detailArray1.size(); j++) {
                        JSONObject detailsArrayJSONObject = detailArray1.getJSONObject(j);
                        Map<String, Object> detailMap = objectMapper.readValue(detailsArrayJSONObject.toString(), Map.class);
                        //先查询是否存在不存在新增
//                        String sql = "select * from uf_sapgysxx_dt1 where mainId = ? and yxszgj = ? and yxzh =? and zhcyr = ? and yxlxh = ? and zhmc =?";
//                        RecordSet recordSet1 = new RecordSet();
//                        recordSet1.executeQuery(sql, mainId, detailsArrayJSONObject.getString("yxszgj"), detailsArrayJSONObject.getString("yxzh"), detailsArrayJSONObject.getString("zhcyr")
//                                , detailsArrayJSONObject.getString("yxlxh"), detailsArrayJSONObject.getString("zhmc")
//                        );
//                        recordSet1.next();
//                        if (recordSet1.getCounts() == 0) {
                            detailMap.put("mainId", mainId);
                            writeLog("=========insertGysxx====uf_sapgysxx_dt1:" + JSONObject.toJSONString(detailMap));
                            insetDetailData("uf_sapgysxx_dt1", detailMap);
//                        } else {
//                            Map<String, Object> whereMap = new HashMap<>();
//                            whereMap.put("mainId", mainId);
//                            writeLog("=========updateGysxx====uf_sapgysxx_dt1+detailMap:" + JSONObject.toJSONString(detailMap));
//                            writeLog("=========updateGysxx====uf_sapgysxx_dt1+whereMap:" + JSONObject.toJSONString(whereMap));
//                            boolean b1 = updateModeData("uf_sapgysxx_dt1", detailMap, whereMap);
//                            writeLog("========insertGysxx=====updateDetail11:" + b1);
//                        }


                    }
                }
            }
            resultMap.put("status", "ok");
        } catch (Exception e) {
            resultMap.put("status", "error");
            resultMap.put("message", e.toString());
            writeLog("=============error:" + e.getMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    /**
     * 物料主数据同步修改接口
     *
     * @param request
     * @param response
     * @param Data
     * @return
     */
    @POST
    @Path("/materialMaster")
    @Produces(MediaType.APPLICATION_JSON)
    public String materialMaster(@Context HttpServletRequest request, @Context HttpServletResponse response, @Valid @RequestBody String Data) {
        Map<String, Object> resultMap = new HashMap<>();
        writeLog("==========materialMaster===Data:" + Data);
        RecordSet recordSet = new RecordSet();
        //查询主表
        String select = "select * from uf_wlbd where wlbm = ?";
        String mainId = "";
        Map<String, Object> mainMap = new HashMap<>();
        int modeId = getModeId("uf_wlbd");
        try {
            //单独处理数据映射
            JSONArray jsonArray = materialMasterData(Data);
            writeLog("==========materialMaster===jsonArray:" + jsonArray);
            ObjectMapper objectMapper = new ObjectMapper();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Map<String, Object> bodyMap = objectMapper.readValue(jsonObject.toString(), Map.class);
                Object VBELN = bodyMap.get("wlbm");
                if (VBELN == null || "".equals(VBELN)) {
                    resultMap.put("status", "error");
                    resultMap.put("message", "物料编码不能为空");
                    return JSONObject.toJSONString(resultMap);
                }
                //主表数据
                mainMap.putAll(bodyMap);
                mainMap.remove("DETAILS");
                //明细表数据
                String DETAILS = jsonObject.getString("DETAILS");
                writeLog("==========materialMaster===DETAILS:" + DETAILS);
                if (DETAILS == null || "".equals(DETAILS)) {
                    resultMap.put("status", "error");
                    resultMap.put("message", "明细不能为空");
                    return JSONObject.toJSONString(resultMap);
                }
                JSONArray detailsArray = JSONObject.parseArray(DETAILS);
                writeLog("==========materialMaster===detailsArray:" + detailsArray);
                recordSet.executeQuery(select, VBELN.toString());
                if (recordSet.next()) {
                    mainId = recordSet.getString("ID");
                }
                if (recordSet.getCounts() == 0) {//新增
                    writeLog("==========materialMaster===mainMap:" + mainMap);
                    boolean b1 = insetModeData("uf_wlbd", mainMap, 1, modeId);
                    writeLog("======materialMaster=======insert:" + b1);
                    //查mainid
                    recordSet.executeQuery(select, VBELN.toString());
                    if (recordSet.next()) {
                        mainId = recordSet.getString("ID");
                    }
                    writeLog("========materialMaster=====mainId1:" + mainId);
                    for (int j = 0; j < detailsArray.size(); j++) {
                        JSONObject detailsArrayJSONObject = detailsArray.getJSONObject(j);
                        Map<String, Object> detailMap = objectMapper.readValue(detailsArrayJSONObject.toString(), Map.class);
                        detailMap.put("mainId", mainId);
                        writeLog("=========materialMaster====mainId2:" + mainId);
                        boolean b = insetDetailData("uf_wlbd_dt1", detailMap);
                        writeLog("=======materialMaster======insertDetail:" + b);
                    }
                } else {
                    //修改主表数据
                    Map<String, Object> whereMap1 = new HashMap<>();
                    whereMap1.put("ID", mainId);
                    boolean b1 = updateModeData("uf_wlbd", mainMap, whereMap1);
                    //修改明细表数据
                    for (int j = 0; j < detailsArray.size(); j++) {
                        JSONObject detailsArrayJSONObject = detailsArray.getJSONObject(j);
                        Map<String, Object> detailMap = objectMapper.readValue(detailsArrayJSONObject.toString(), Map.class);
                        Object posnr = detailMap.get("gc");
                        if (posnr == null || "".equals(posnr)) {
                            resultMap.put("status", "error");
                            resultMap.put("message", "工厂不能为空");
                            return JSONObject.toJSONString(resultMap);
                        }
                        //查询明细表
                        String selectDetail = "select * from uf_wlbd_dt1 where gc = ? AND MAINID = ?";
                        recordSet.executeQuery(selectDetail, posnr.toString(), mainId);
                        recordSet.next();
                        if (recordSet.getCounts() != 0) {//修改明细表
                            Map<String, Object> whereMap = new HashMap<>();
                            whereMap.put("gc", posnr.toString());
                            whereMap.put("mainId", mainId);
                            boolean b = updateModeData("uf_wlbd_dt1", detailMap, whereMap);
                            writeLog("========materialMaster=====updateDetail11:" + b);
                        } else {//新增明细表
                            detailMap.put("mainId", mainId);
                            boolean b = insetDetailData("uf_wlbd_dt1", detailMap);
                            writeLog("========materialMaster=====insertDetail22:" + b);
                        }
                    }
                }
            }
            resultMap.put("status", "ok");
        } catch (Exception e) {
            resultMap.put("status", "error");
            resultMap.put("message", e.toString());
            writeLog("========materialMaster=====error:" + e.getMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    //单独处理数据
    public JSONArray materialMasterData(String data) throws JSONException {
        JSONArray jsonArray = JSONObject.parseArray(data);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            jsonObject.put("wlbm", Util.null2String(jsonObject.get("MARA-MATNR")));
            jsonObject.remove("MARA-MATNR");

            jsonObject.put("wlms", Util.null2String(jsonObject.get("MAKT-MAKTX")));
            jsonObject.remove("MAKT-MAKTX");

            jsonObject.put("ggxh", Util.null2String(jsonObject.get("MARA-GROES")));
            jsonObject.remove("MARA-GROES");

            jsonObject.put("wlcms", Util.null2String(jsonObject.get("ZTEXT1")));
            jsonObject.remove("ZTEXT1");

            jsonObject.put("wllx", Util.null2String(jsonObject.get("MARA-MTART")));
            jsonObject.remove("MARA-MTART");

            jsonObject.put("wlz", Util.null2String(jsonObject.get("MARA-MATKL")));
            jsonObject.remove("MARA-MATKL");

            jsonObject.put("jbdw", Util.null2String(jsonObject.get("MARA-MEINS")));
            jsonObject.remove("MARA-MEINS");

            jsonObject.put("jwlh", Util.null2String(jsonObject.get("MARA-BISMT")));
            jsonObject.remove("MARA-BISMT");

            jsonObject.put("tym", Util.null2String(jsonObject.get("MARA-ZNAME2")));
            jsonObject.remove("MARA-ZNAME2");

            jsonObject.put("spmc", Util.null2String(jsonObject.get("MARA-ZNAME")));
            jsonObject.remove("MARA-ZNAME");

            JSONArray details = jsonObject.getJSONArray("DETAILS");
            if (details.size() != 0) {
                for (int i1 = 0; i1 < details.size(); i1++) {
                    JSONObject jsonObject1 = details.getJSONObject(i1);
                    jsonObject1.put("gc", Util.null2String(jsonObject1.get("MARC-WERKS")));
                    jsonObject1.remove("MARC-WERKS");

                    jsonObject1.put("cgz", Util.null2String(jsonObject1.get("MARC-EKGRP")));
                    jsonObject1.remove("MARC-EKGRP");

                    jsonObject1.put("pcgl", Util.null2String(jsonObject1.get("MARC-XCHPF")));
                    jsonObject1.remove("MARC-XCHPF");

                    jsonObject1.put("cgdw", Util.null2String(jsonObject1.get("MARA-BSTME")));
                    jsonObject1.remove("MARA-BSTME");

                    jsonObject1.put("jhjhsj", Util.null2String(jsonObject1.get("MARC-PLIFZ")));
                    jsonObject1.remove("MARC-PLIFZ");

                    jsonObject1.put("shclsj", Util.null2String(jsonObject1.get("MARC-WEBAZ")));
                    jsonObject1.remove("MARC-WEBAZ");

                    jsonObject1.put("zljy", Util.null2String(jsonObject1.get("ZZLJY")));
                    jsonObject1.remove("ZZLJY");

                    jsonObject1.put("djbs", Util.null2String(jsonObject1.get("ZDJBS")));
                    jsonObject1.remove("ZDJBS");
                }
            }
        }
        return jsonArray;
    }


    /**
     * 插入到建模明细表数据
     *
     * @param tableName
     * @param data
     * @return
     * @throws Exception
     */
    public static boolean insetDetailData(String tableName, Map<String, Object> data) throws Exception {
        List<Object> dataList = new ArrayList<>();
        String columns = "";
        String values = "";
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value != null && !value.equals("")) {
                columns += (key + ",");
                values += ("?,");
                dataList.add(value);
            }
        }

        if (columns.endsWith(",")) {
            columns = columns.substring(0, columns.length() - 1);
        }
        if (values.endsWith(",")) {
            values = values.substring(0, values.length() - 1);
        }

        String insertSql = "insert into  " + tableName + "(" +
                columns +
                ") values(" +
                values + ")";
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("===========insertSql", insertSql);
        RecordSet insertRs = new RecordSet();
        boolean b1 = insertRs.executeUpdate(insertSql, dataList.toArray());
        return b1;
    }

    public static boolean insetModeData(String tableName, Map<String, Object> data, int hrmResourceId, int modeId) throws Exception {
        List<Object> dataList = new ArrayList<>();
        String columns = "";
        String values = "";
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value != null && !value.equals("")) {
                columns += (key + ",");
                values += ("?,");
                dataList.add(value);
            }

        }
        BaseBean baseBean = new BaseBean();
        String insertSql = "insert into  " + tableName + "(" +
                columns +
                " formmodeid," +
                " modedatacreater," +
                " modedatacreatertype," +
                " modedatacreatedate," +
                " modedatacreatetime, " +
                " MODEUUID" +
                ") values(" +
                values +
                "?,?,?,?,?,?)";
        baseBean.writeLog("===========insertSql", insertSql);
        String currentDateString = TimeUtil.getCurrentDateString();
        String currentTimeString = TimeUtil.getOnlyCurrentTimeString();
        String uuid = UUID.randomUUID().toString();

        Object[] objects = new Object[]{
                modeId, hrmResourceId, 0, currentDateString, currentTimeString, uuid
        };
        dataList.addAll(Arrays.asList(objects));

        RecordSet insertRs = new RecordSet();
        boolean b1 = insertRs.executeUpdate(insertSql, dataList.toArray());
        if (b1) {
            RecordSet recordSet1 = new RecordSet();
            recordSet1.executeQuery("select max(id) as billid from " + tableName + " ");
            if (recordSet1.next()) {
                int billid = recordSet1.getInt("billid");
                ModeRightInfo ModeRightInfo = new ModeRightInfo();
                ModeRightInfo.setNewRight(true);
                ModeRightInfo.editModeDataShare(1, modeId, billid);
            }
        }
        return b1;
    }


    public static boolean updateModeData(String tableName, Map<String, Object> data, Map<String, Object> updateData) throws Exception {
        String columns = "";
        String updateColumns = "";
        // 处理 SET 部分
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null || value.equals("")) {
                columns += key + " = NULL, ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    columns += key + " = '', ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    columns += key + " = '" + escaped + "', ";
                }
            } else {
                columns += key + " = " + value + ", ";
            }
        }

        // 处理 WHERE 条件
        for (Map.Entry<String, Object> stringObjectEntry : updateData.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                updateColumns += key + " = NULL AND ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    updateColumns += key + " = '' AND ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    updateColumns += key + " = '" + escaped + "' AND ";
                }
            } else {
                updateColumns += key + " = " + value + " AND ";
            }
        }

        String insertSql = "update  " + tableName + " set " + columns;
        if (insertSql.endsWith(", ")) {
            insertSql = insertSql.substring(0, insertSql.length() - 2);
        }
        insertSql = insertSql + " where ";
        if (updateColumns.endsWith("AND ")) {
            updateColumns = updateColumns.substring(0, updateColumns.length() - 4);
        }
        insertSql = insertSql + updateColumns;
        RecordSet updateRs = new RecordSet();
        return updateRs.executeUpdate(insertSql);
    }


    /**
     * @param tablename
     * @return
     */
    public static int getModeId(String tablename) {
        RecordSet rs = new RecordSet();
        Map<String, Integer> map = new HashMap<>();
        rs.executeQuery("select b.tablename,a.formid,b.detailkeyfield,a.id from modeinfo a,workflow_bill b where a.formid = b.id  and tablename=?", tablename);
        if (rs.next()) {
            int id = rs.getInt("id");
            return id;
        }
        return 0;
    }

}
